package com.uw.uwrpc.core.cluster.loadbalancer;

import com.uw.uwrpc.core.api.LoadBalancer;
import com.uw.uwrpc.core.meta.InstanceMeta;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalancer implements LoadBalancer<InstanceMeta> {

    private final AtomicInteger sum = new AtomicInteger();

    @Override
    public InstanceMeta choose(List<InstanceMeta> instanceList) {

        if (CollectionUtils.isEmpty(instanceList)) {
            return null;
        }
        if (instanceList.size() == 1) {
            return instanceList.get(0);
        }

        return instanceList.get((sum.incrementAndGet() & 0x7fffffff) % instanceList.size());
    }
}
